import Vue from 'vue'
import App from './App'
import base from 'common/base.js'

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
	...App
})
app.$mount()


/**
 * @param {Object} backpage
 * @param {Object} backtype
 */
Vue.prototype.checkLogin = function() {
	// 同步获取本地数据（uid、随机码、用户名、头像）
	var user = uni.getStorageSync('user')
	console.log(user)
	if (user == '' || user == undefined) {
		// 使用重定向的方式跳转至登录页面
		uni.redirectTo({
			url: 'login'
		});
		return false;
	}
	// 登录成功、已经登录返回数组 [用户 id, 用户随机码, 用户昵称, 用户表情]
	return user;
}

Vue.prototype.config = base.config

var socket
/**
 * 建立websocket连接
 * @param {Object} userId
 */
Vue.prototype.wsConnect = function(userId) {
	var socketUrl = this.config.baseURL + "/imserver/" + userId
	socketUrl = socketUrl.replace("https", "ws").replace("http", "ws")
	if (socket != null) {
		socket.close()
		socket = null
	}
	socket = uni.connectSocket({
		url: socketUrl,
		complete: () => {}
	});
	//打开事件
	socket.onOpen = function() {
		console.log("websocket已打开")
		//socket.send("这是来自客户端的消息" + location.href + new Date());
	};
	socket.onOpen(() => {
		console.log('conn')
	})
	socket.onMessage(res => {
		console.log(res)
	})
	socket.onClose(() => {
		console.log('close')
	})
	socket.onError((err) => {
		console.log(err)
	})
}
/**
 * 发送消息
 * @param {Object} userId
 * @param {Object} msg
 */
Vue.prototype.sendMessage = function(userId, msg) {
	socket.send('{"toUserId":"' + userId + '","contentText":"' + msg + '"}');
}
